package com.sjq.common.web;



import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by gaox on 2017/3/7.
 */
public class SessionHelper {
    private HttpSession session = null;

    private SessionHelper(HttpSession session) {
        this.session = session;
    }

    private SessionHelper(HttpServletRequest request) {
        this.session = request.getSession();
    }

    public static SessionHelper create(HttpSession session) {
        return new SessionHelper(session);
    }

    public ServletContext getServletContext(){
        return session.getServletContext();
    }

    public static SessionHelper create(HttpServletRequest request) {
        return new SessionHelper(request);
    }


    private HttpSession getSession() {
        if (session == null) {
            throw new NullPointerException("session is null");
        }

        return session;
    }

    public <T> void setAttribute(String key, T value) {
        this.getSession().setAttribute(key, value);
    }

    public void removeAttribute(String key){
        this.getSession().removeAttribute(key);
    }

    public <T> T getAttribute(String key, Class<T> clazz) {
        if (key.equals("")) {
            throw new NullPointerException("key is null or empty");
        }
        Object value = getSession().getAttribute(key);
        if (value == null) return null;

        if (!clazz.isInstance(value)) {
            throw new IllegalArgumentException(
                    String.format("T parameter is error,please check call paramater %n [expect=%s, real=%s]",
                            value.getClass().getName(), clazz.getName()));
        }

        return (T) value;
    }
}
